package org.hong.microservice.authentication.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * Created by victor on 2020/3/30 11:24.
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .mvcMatchers("/h2-console/**", "/h2-console/login.do").permitAll()
                .anyRequest().authenticated()
                .and()
            .httpBasic()
                .and()
            .csrf().ignoringRequestMatchers(
                    request -> "/introspect".equals(request.getRequestURI()),
                    request -> request.getRequestURI().contains("h2-console")
            ).and()
                .headers().frameOptions().sameOrigin();
    }

    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        return new InMemoryUserDetailsManager(
            User.withDefaultPasswordEncoder()
                .username("subject")
                .password("password")
                .roles("USER")
                .build(),
            User.withDefaultPasswordEncoder()
                .username("cai")
                .password("password")
                .roles("CLIENT")
                .build()
        );
    }
}
